package top.lvkun.product.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.lvkun.basic.service.impl.BaseServiceImpl;
import top.lvkun.product.domain.Product;
import top.lvkun.product.domain.ProductDetail;
import top.lvkun.product.mapper.ProductMapper;
import top.lvkun.product.service.IProductService;
import top.lvkun.user.mapper.ShopcartMapper;

import java.util.Date;
import java.util.List;

@Service
public class ProductServiceImpl extends BaseServiceImpl<Product> implements IProductService {
    @Autowired
    private ProductMapper productMapper;
    private ShopcartMapper shopcartMapper;

    @Override
    @Transactional
    public void AddOrUpdate(Product product) {
        if (product.getId()==null){//新增
            //先保存t_product表数据，并返回主键
            System.out.println(product.getShop_id());
            productMapper.save(product);
            ProductDetail productDetail = product.getProductDetail();
            productDetail.setProduct_id(product.getId());
            productMapper.saveProductDetail(productDetail);
        }else {
            productMapper.update(product);
            productMapper.updateProductDetail(product.getProductDetail());
        }

    }

    /**
     * 批量上架
     * @param ids
     */
    @Override
    @Transactional
    public void patchUp(List<Long> ids) {
        for (Long id : ids) {
            Product product = productMapper.loadById(id);
            product.setState(0);
            product.setOnsaletime(new Date());
            productMapper.update(product);
        }
    }

    /**
     * 批量下架
     * @param ids
     */
    @Override
    @Transactional
    public void patchDown(List<Long> ids) {
        for (Long id : ids) {
            Product product = productMapper.loadById(id);
            product.setState(1);
            product.setOnsaletime(product.getOffsaletime());
            product.setOffsaletime(new Date());
            productMapper.update(product);
        }
    }

    /**
     * 删除产品的同时删除产品详细,以及购物车里面产品
     * @param id
     */
    @Override
    @Transactional
    public void del(Long id) {
        /*Product product = productMapper.loadById(id);
        Long detailID = product.getProductDetail().getId();*/
        super.del(id);
        productMapper.delProductDetail(id);
        //通过product_id删除购物车里面的数据
        shopcartMapper.del(id);
    }
}
